package MQ.Exchange.Topic;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * @Title: MQ.WorkQueues.NewTask.java
 * @Package MQ.WorkQueues
 * @Description: TODO(MQ消息发送到topic的交换机上)
 * @Copyright: Copyright (c) 2017 YUANH All Rights Reserved
 * @author yuanh
 * @date 2017-5-10 下午3:50:35
 */
public class NewTask {
	private final static String EXCHANGE_NAME = "topic_logs";
	private final static String QUEUE_NAME = "hello_topic";
	private final static String QUEUE_NAME2 = "hello_topic1";
	private final static String[] topicStr = new String[] { "*.orange.*" };
	private final static String[] topicStr2 = new String[] { "*.*.rabbit","lazy.#" };

	public static void main(String[] args) throws IOException, TimeoutException {
		// 创建连接连接到MabbitMQ
		ConnectionFactory factory = new ConnectionFactory();
		// 设置MabbitMQ所在主机ip或者主机名
		factory.setHost("127.0.0.1");
		factory.setUsername("yuanh");
		factory.setPassword("yuanh");
		factory.setPort(5672);
		factory.setVirtualHost("y_yuanh");
		Connection connection = factory.newConnection();
		// 创建一个频道
		Channel channel = connection.createChannel();
		// 声明队列、设置队列持久化
		boolean durable = true;
		channel.queueDeclare(QUEUE_NAME, durable, false, false, null);
		channel.queueDeclare(QUEUE_NAME2, durable, false, false, null);
		// 声明fanout交换机、设置持久化
		boolean durable2 = true;
		channel.exchangeDeclare(EXCHANGE_NAME, "topic", durable2);
		// 将队列绑定到交换机上
		for (String severity : topicStr) {
			channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, severity);
		}
		for (String severity : topicStr2) {
			channel.queueBind(QUEUE_NAME2, EXCHANGE_NAME, severity);
		}
		String message = "quick.orange.rabbit";
		String message2 = "lazy.orange.elephant";
		String message3 = "lazy.pink.rabbit";
		String message4 = "quick.brown.fox";
		// 将消息放到队列里面
		// channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
		// 将消息放到交换机上
		channel.basicPublish(EXCHANGE_NAME, message, null, message.getBytes());
		channel.basicPublish(EXCHANGE_NAME, message2, null, message2.getBytes());
		channel.basicPublish(EXCHANGE_NAME, message3, null, message3.getBytes());
		channel.basicPublish(EXCHANGE_NAME, message4, null, message4.getBytes());
		System.out.println(" 发送 '" + message + "'");
		System.out.println(" 发送 '" + message2 + "'");
		System.out.println(" 发送 '" + message3 + "'");
		System.out.println(" 发送 '" + message4 + "'");
		// 关闭通道和连接
		channel.close();
		connection.close();
	}


}